package pre_start

import (
	"github.com/astaxie/beego"
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"haproxy-mgr-go/clusters"
	"haproxy-mgr-go/models/nodes"
	"strings"
	"os"
	"haproxy-mgr-go/models"
	"haproxy-mgr-go/haproxy"
)

var Cfg = beego.AppConfig
var RunMode string

func init() {
	//初始化配置
	initEnv()

	initClusers()

	initHaproxy()
}

func initClusers() {
	list := clusters.StartServ()

	localIP := list.LocalNode().Addr

	ns := nodes.FindAll()

	var nodelist []string

	if len(ns) > 0 {
		for _, node := range ns {
			valid := clusters.CheckNode(&node)
			if !valid {
				nodes.DelNodes(&node)
			}else {
				addrStr := node.ClusterListnerAddress
				nodeIP := strings.Split(addrStr, ":")[0]
				if nodeIP == localIP.String() {
					nodes.DelNodes(&node)
				} else {
					nodelist = append(nodelist, addrStr)
				}
			}
		}
	}

	if len(nodelist) > 0 {
		list.Join(nodelist)
	}

	nodeName,_ := os.Hostname()
	nodeAddr := localIP.String()
	node := &models.Nodes{Name:nodeName, ClusterListnerAddress:nodeAddr}
	nodes.AddNodes(node)

	go clusters.SyncMembers(list)
}

func initEnv()  {
	// database
	dbUser := Cfg.String("db_user")
	dbPass := Cfg.String("db_pass")
	dbHost := Cfg.String("db_host")
	dbPort := Cfg.String("db_port")
	dbName := Cfg.String("db_name")
	maxIdleConn, _ := Cfg.Int("db_max_idle_conn")
	maxOpenConn, _ := Cfg.Int("db_max_open_conn")
	dbLink := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", dbUser, dbPass, dbHost, dbPort, dbName)

	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", dbLink, maxIdleConn, maxOpenConn)

	RunMode = Cfg.String("runmode")
	if RunMode == "dev" {
		orm.Debug = true
	}
}

func initHaproxy() {
	haproxy.InitHAConf()
	haproxy.StartServ()
}



